package MultiThread;

import java.util.concurrent.CountDownLatch;

public class MultiThreadAdd {
    /*
    真正实现用多线程来计算累加 例如用两个线程计算从1加到100
     */
    public static void main(String[] args) throws InterruptedException {
        long n = 100;
        CountDownLatch latch = new CountDownLatch(2);
        AddTask a1 = new AddTask(1, n / 2, latch);
        AddTask a2 = new AddTask(n / 2 + 1, n, latch);
        Thread t1 = new Thread(a1, "t1");
        Thread t2 = new Thread(a2, "t2");
        t1.start();
        t2.start();
        latch.await();
        System.out.println(a1.getAns() + a2.getAns());

    }
}


class AddTask implements Runnable {
    long begin;
    long end;
    long ans;
    CountDownLatch latch;
    public long getAns() throws InterruptedException {
        latch.await();
        return ans;
    }
    public AddTask() {}
    public AddTask(long begin, long end, CountDownLatch latch) {
        this.begin = begin;
        this.end = end;
        this.latch = latch;
    }
    @Override
    public void run() {
        ans = 0;
        System.out.println(Thread.currentThread().getName());
        for (long i = begin; i <= end; i++) {
            ans += i;
        }
        latch.countDown();
    }
}
